import {ChangeDetectorRef, Component, ViewChild} from '@angular/core';
import {AlertController, Content, IonicPage, NavController, NavParams, Select, ToastController} from 'ionic-angular';
import {ExtensionEidtProvider} from "../../../providers/client/extension-eidt/extension-eidt.provider";
import {ParamModel, PageClientMod} from "../../../model/pages/client/extension-edit/extension-edit.model"
import {MessageBushService} from "../../../services/common/message-bush.service";
import {ClientAddProvider} from '../../../providers/client/client-add/client-add.provider';
import {LoadingService} from "../../../services/common/loading.service";


/**
 * 编辑核心客户扩展信息
 */

@IonicPage()
@Component({
    selector: 'page-extension-eidt',
    templateUrl: 'extension-eidt.html',
    providers: [
        ExtensionEidtProvider,
        ClientAddProvider
    ]
})
export class ExtensionEidtPage {
    // 客户总信息
    private clientsModel: PageClientMod = new PageClientMod();

    public testPhone: RegExp = /^[0-9]*$/;
    public phone = false;
    public address = false;
    public detail;
    public isDisabled = false;
    // 传参 model 信息
    private clientsParamsMod :ParamModel = new ParamModel();
//表单验证提示信息
    public FormTip = {
        phone: "请填写正确的电话",
        postCode: "请填写正确的邮编",
        addressTip: "地址不能为空",
        otherIns: "请选择保险类型",
    };
    @ViewChild(Content) content: Content;

    @ViewChild("select1") select1: Select;
    @ViewChild("select2") select2: Select;
    @ViewChild("select3") select3: Select;
    @ViewChild("select4") select4: Select;
    @ViewChild("select5") select5: Select;
    @ViewChild("select6") select6: Select;

    constructor(public navCtrl: NavController,
                public navParams: NavParams,
                private ref: ChangeDetectorRef,
                public toastCtrl: ToastController,
                public alert: AlertController,
                public extensionEidt: ExtensionEidtProvider,
                public cliAddPro: ClientAddProvider,
                public load:LoadingService) {

    }
    public scrollHeight = 0;
    ionViewDidLoad() {
        this.getExtensionCust();
        this.scrollHeight = $('.scroll-content')[$('.scroll-content').length - 1].scrollTop;

    }

    ionViewWillLeave(){
        this.select1.close();
        this.select2.close();
        this.select3.close();
        this.select4.close();
        this.select5.close();
        if(this.select6){
            this.select6.close();
        }

    }
    /**
     * 初始化扩展字段编辑页面
     */
    getExtensionCust() {
        this.detail = this.navParams.get('data');
        this.clientsModel.userId = this.detail.clientId;
        if (this.detail) {
            this.clientsModel  = JSON.parse(JSON.stringify(this.navParams.get('data')));
            this.initPhoneAndAdd();
        }
    }
    /**
     *  滚动失光标
     */
    onScroll() {
        this.scrollHeight = $('.scroll-content')[$('.scroll-content').length - 1].scrollTop;
    }
    /**
     * 初始化手机和地址
     */
    initPhoneAndAdd() {
        if (this.clientsModel.mobilePhone && this.clientsModel.mobilePhone.length) {
            this.clientsModel.mobilePhone.forEach((res, i) => {
                if (res.defaultIndicator == "1" && !res.mobile) {
                    this.clientsModel.mobilePhone.splice(i, 1);
                    if (this.clientsModel.mobilePhone.length == 0) {
                        this.clientsModel.mobilePhone = [{
                            "id": "",
                            "mobile": "",
                            "defaultIndicator": "0",
                            'individual': false
                        }];
                    }
                }
            });
        } else {
            this.clientsModel.mobilePhone = [{"id": "", "mobile": "",
                "defaultIndicator": "0", 'individual': false}];
        }
        if (this.clientsModel.addressList && this.clientsModel.addressList.length) {
            this.clientsModel.addressList.forEach((res, i) => {
                if (res.individual == true && !res.address && !res.postCode) {
                    this.clientsModel.addressList.splice(i, 1);
                }
            });
        } else {
            this.clientsModel.addressList = [{
                address: '',
                defaultIndicator: "1",
                id: "",
                postCode: "",
                individual: false,
            }];
        }
    }

    /**
     * 页面表单验证\提示
     */
    getCheckData(data, ev) {
        const testPhone: RegExp = /^[0-9]*$/;
        let phoneTip: boolean = true;
        let postCodeTip: boolean = true;
        let addressTip: boolean = true;
        let addressList2 = [];
        if (data.mobilePhone && data.mobilePhone.length) {
            for (let i = 0; i < data.mobilePhone.length; i++) {
                if (data.mobilePhone.length && data.mobilePhone[i].mobile && testPhone.test(data.mobilePhone[i].mobile) == false) {
                    phoneTip = false;
                }
            }
        }
        if (data.addressList && data.addressList.length) {
            for (let i = 0; i < data.addressList.length; i++) {
                if (data.addressList[i].postCode && testPhone.test(data.addressList[i].postCode) == false) {
                    postCodeTip = false;
                }
                //有邮编的地址不能为空
                if (!data.addressList[i].address && data.addressList[i].postCode) {
                    addressTip = false;
                }
                if (data.addressList[i].address) {
                    addressList2.push(data.addressList[i]);
                }
            }
        }

        data.addressList = addressList2;
        if(data.addressList.length){
            let ddd = [];
            // 判断参数中是否设置了默认地址
            for (let j = 0; j < data.addressList.length; j++) {
                ddd.push(Number(data.addressList[j].defaultIndicator));
            }
            let aaa = [];
            let bbb = [];
            //判断是否有核心地址
            for (let q = 0; q < this.detail.addressList.length; q++) {
                aaa.push(Number(this.detail.addressList[q].individual));
                bbb.push(Number(this.detail.addressList[q].defaultIndicator));
            }
            if (ddd.indexOf(1) == -1 && aaa.indexOf(true) == -1 && bbb.indexOf(1) == -1) {
                data.addressList[0].defaultIndicator = "1";
            }
        }

        if (phoneTip == false) {
            this.toast(this.FormTip.phone, "bottom");
            return false;
        }else if (data.otherIns == 1 && !data.insType) {
            this.toast(this.FormTip.otherIns, "bottom");
            return false;
        }  else if (addressTip == false) {
            this.toast(this.FormTip.addressTip, "bottom");
            return false;
        } else if (postCodeTip == false) {
            this.toast(this.FormTip.postCode, "bottom");
            return false;
        } else {
            return true;
        }
    }

    /**
     * 保存前验证电话姓名
     * @param ev
     */
    checkClient(ev) {
        this.clientsParamsMod = ParamModel.EditParmMod(JSON.parse(JSON.stringify(this.clientsModel)));
        let par = this.clientsParamsMod;
        if (!this.getCheckData(par, ev)) {
            return;
        }
        this.isDisabled = true;
        let mobilePhone2 = [];
        if(par.mobileList && par.mobileList.length){
            for (let i = 0; i < par.mobileList.length; i++) {
                // 删除空电话
                if (par.mobileList[i].mobile && !par.mobileList[i].individual) {
                    mobilePhone2.push(par.mobileList[i]);
                }
            }
        }
        par.mobileList = mobilePhone2;
        let data = {
            'mobileList': par.mobileList,
            'name': this.detail.name,
            'userId': this.detail.clientId
        };
        this.load.showLoading();
        this.cliAddPro.checkCustomer(data).subscribe((res) => {
            this.addExtensionCust();
        }, error => {
            this.load.dismissLoading();
            this.isDisabled = false;
            if (error.status == 500) {
                if(JSON.parse(error.error).status==999){
                    if (JSON.parse(error.error).exception == "Prospect already exist") {
                        this.toast("客户已存在", "middle");
                    } else if (JSON.parse(error.error).exception == "Mobile already exist") {
                        this.alert.create({
                            title: '电话已经存在',
                            message: '电话已经存在,是否继续添加？',
                            cssClass:'ifAddCustExt',
                            buttons: [{
                                text: '取消', handler: () => {
                                    this.isDisabled = false;
                                }
                            }, {
                                text: '确定', handler: () => {
                                    this.addExtensionCust(1);
                                }
                            }]
                        }).present();
                    }
                } else {
                    this.isDisabled = false;
                }
            }else{
                this.toast('网络错误，请重试!', "middle");
            }
        })
    }

    /**
     * 保存扩展信息
     */
    addExtensionCust(loading = 0) {
        this.clientsParamsMod.customerId = this.detail.customerId;
        this.clientsParamsMod.partyId = this.detail.partyId;
        this.clientsParamsMod.clientId = this.detail.clientId;
        this.clientsParamsMod.name = this.detail.name;
        this.clientsParamsMod.otherIns = this.clientsModel.otherIns;
        this.clientsParamsMod.insType = this.clientsModel.insType;
        if (loading) {
            this.load.showLoading();
        }
        this.extensionEidt.addExtensionCustomer(this.clientsParamsMod).subscribe(res => {
            MessageBushService.setMessage(MessageBushService.keys.clientDetailDataUpdated, '1');
            MessageBushService.setMessage(MessageBushService.keys.clientFilterListUpdated, '1');
            MessageBushService.setMessage(MessageBushService.keys.clientIndividualClientUpdated, '1');
            MessageBushService.setMessage(MessageBushService.keys.favoriteIsUpdated, '1');
            MessageBushService.setMessage(MessageBushService.keys.clientMapCustomerDetailUpdated, '1');
            MessageBushService.setMessage(MessageBushService.keys.vipClientListUpdated, '1');
            MessageBushService.setMessage(MessageBushService.keys.compensationClientListUpdated,'1');
            MessageBushService.setMessage(MessageBushService.keys.birthdayClientListUpdated,'1');
            MessageBushService.setMessage(MessageBushService.keys.renewalClientListUpdated,"1");
            this.load.dismissLoading();
            this.toast("保存成功", "bottom");
            this.backToProPage();
            this.isDisabled = false;
        }, (err) => {
             // if(JSON.parse(err.error).status==999){
                this.toast('网络错误,请重试！','middle');
            // }
            this.load.dismissLoading();
            this.isDisabled = false;
        });
    }

    /**
     *  设置默认地址
     * @param index
     */
    setDefaultAddress(index,isDefault) {
        if(isDefault == 1)return;
        let def = this.clientsModel.addressList;
        for (let a = 0; a < def.length; a++) {
            if (index == a && !Number(def[a].defaultIndicator)) {
                def[a].defaultIndicator = '1';
            } else if (def.length > 1) {
                def[a].defaultIndicator = '0';
            }
        }
    }

    /**
     * 添加新手机
     */
    addNewPhone(ev) {
        ev.preventDefault();
        ev.stopPropagation();
        this.clientsModel.mobilePhone.push({mobile: '', id: "",
            defaultIndicator: "0", individual: false});
        this.ref.detectChanges()
    }


    /**
     * 输入电话号码
     */
    inputOnchange(i, ele, a ,ev) {
        let val = ev.value.replace(/[^0-9]/ig, '');
        // if (ev.value.length > 1) {
        //     //当大于1位数的时候，去掉第一个0
        //     val = val.replace(/^[0]+/, '');
        // }
        ev.value = val;
        this.clientsModel.mobilePhone[i].mobile =val;
    }
    /**
     * 删除手机号
     */
    delLocalPhone(ind, ev, data,isEmpty) {
        ev.preventDefault();
        ev.stopPropagation();
        this.clientsModel.mobilePhone.splice(ind, 1);
        this.ref.detectChanges()
    }

    /**
     * 添加新地址
     */
    addNewAddress(ev) {
        ev.preventDefault();
        ev.stopPropagation();
        this.clientsModel.addressList.push({
            address: '',
            defaultIndicator: "0",
            id: "",
            postCode: "",
            individual: false
        });
        if (this.clientsModel.addressList.length === 1) {
            this.clientsModel.addressList[0].defaultIndicator = '1';
        }
        this.ref.detectChanges();
    }

    /**
     * 删除地址
     */
    delLocalAddress(ind, ev) {
        ev.preventDefault();
        ev.stopPropagation();

        if ((this.clientsModel.addressList.length  && Number(this.clientsModel.addressList[ind].defaultIndicator))) {
            this.clientsModel.addressList[0].defaultIndicator = "1";
        }
        this.clientsModel.addressList.splice(ind, 1);
        this.ref.detectChanges()
    }
    contentHeight;
    /**
     * input获得焦点
     * @param ev
     */
    inputFocus(ev) {

        ev.stopPropagation();
        ev.preventDefault();
        // 当前屏幕高度..
        this.contentHeight = document.body.clientHeight;

        if ($(ev.target).offset().top > this.contentHeight / 2) {
            this.content.scrollTo(0, $(ev.target.offsetParent).offset().top +
                this.scrollHeight - 200, 500);
        }
        console.log($(ev.target).offset().top)
    }

    /**
     * 地址输入框失去焦点
     */
    inputBlur(i){
        this.clientsModel.addressList[i].address = this.clientsModel.addressList[i].address.toUpperCase();
    }


    /**
     * 输入邮编
     */
    inputOnchangePostCode(i,ev) {
        // if (!this.testPhone.test(ele.value) && ele.value) {
        //     this.toast("邮编只能为数字", 'middle');
        // }

        let val = ev.target.value.replace(/[^0-9]/ig, '');
        if (ev.target.value.length > 1) {
            //当大于1位数的时候，去掉第一个0
            val = val.replace(/^[0]+/, '');
        }
        ev.target.value = val;

        this.clientsModel.addressList[i].postCode = val;

    }

    /**
     *  toast 提示信息
     * @param {string} message 提示内容
     * @param {string} position 显示位置
     */
    toast(message: string, position: string) {
        this.toastCtrl.create({
            message: message,
            position: 'middle',
            duration: 1200
        }).present();
    }


    /**
     *  返回
     */
    backToProPage() {
        this.navCtrl.pop(null);
    }

    otherSelectChoose() {
        if (this.clientsModel.otherIns == 2) {
            this.clientsModel.insType = 0;
        }
    }
}
